package com.java1234.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.java1234.dao.StudentDao;
import com.java1234.model.Student;

@Repository()
public class StudentDaoImpl implements StudentDao {

	@Resource
	private JdbcTemplate jdbcTemplate;

	/*
	 * public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
	 * this.jdbcTemplate = jdbcTemplate; }
	 */

	public int addStudent(Student student) {
		String sql = "insert into t_student values(null,?,?)";
		Object[] par = new Object[] { student.getName(), student.getAge() };
		return jdbcTemplate.update(sql, par);
	}

	public int updateStudent(Student student) {

		String sql = "update t_student set name=?,age=? where id=?";
		Object[] par = new Object[] { student.getName(), student.getAge(),
				student.getId() };
		return jdbcTemplate.update(sql, par);
	}

	public int deleteStudent(int id) {
		String sql = "delete from t_student where id=?";
		Object[] par = new Object[] { id };
		return jdbcTemplate.update(sql, par);
	}

	public List<Student> findStudents() {
		String sql = "select * from t_student";

		final List<Student> studentList = new ArrayList<Student>();

		jdbcTemplate.query(sql, new RowCallbackHandler() {

			public void processRow(ResultSet rs) throws SQLException {

				Student student = new Student();
				student.setId(rs.getInt("id"));
				student.setName(rs.getString("name"));
				student.setAge(rs.getInt("age"));
				studentList.add(student);
			}
		});
		return studentList;
	}

	class StudentRowMapper implements RowMapper<Student> {
		public Student mapRow(ResultSet rs, int index) throws SQLException {
			Student student = new Student();
			student.setId(rs.getInt("id"));
			student.setName(rs.getString("name"));
			student.setAge(rs.getInt("age"));

			return student;
		}
	}

	@Override
	public Student getStudent(int id) {

		String sql = "select * from t_student where id=?";
		return jdbcTemplate.queryForObject(sql, new Object[] { id },
				new StudentRowMapper());
	}

}
